package StudyCode.summary.BufferAndChannel;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.util.LinkedList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CollectionByteBuffer {
	private static final String fileName = "E:/Copy/1.txt";

	public static void main(String[] argv) throws Exception {
		int reps = 10;

		FileOutputStream fos = new FileOutputStream(fileName);
		GatheringByteChannel gatherChannel = fos.getChannel();
		ByteBuffer[] bs = utterBS(reps);
		while (gatherChannel.write(bs) > 0) {

		}
		System.out.println(fileName);

		fos.close();
	}

	private static ByteBuffer[] utterBS(int howMany) throws Exception {
		List list = new LinkedList();
		for (int i = 0; i < howMany; i++) {
			list.add(pickRandom());
			list.add(pickRandom());
			list.add(pickRandom());
		}
		ByteBuffer[] bufs = new ByteBuffer[list.size()];
		list.toArray(bufs);
		return (bufs);
	}

	private static ByteBuffer pickRandom() throws Exception {
		String string = "www.tah1986.com";
		int total = string.length();
		ByteBuffer buf = ByteBuffer.allocate(total);
		buf.put(string.getBytes("US-ASCII"));
		buf.flip();
		return (buf);
	}
}
